﻿using App.IService;
using App.Model.DTO.Classification;
using App.Model.DTO.User;
using App.Model;
using App.Service;
using App.WebAPI.Utilty.ApiResult;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq.Expressions;
using App.Model.DTO.photo;
using App.Common;
using App.Model.DTO.Article;
using COSXML.Common;
using COSXML.Model.Object;
using COSXML;

namespace App.WebAPI.Controllers
{
    [Route("[controller]/[Action]")]
    [ApiController]
    [Authorize]
    public class PhotoController : ControllerBase
    {
        private readonly IPhotoService _iPhotoService;
        private readonly CosXml _cosClient;
        public class PageListRequest
        {
            public int PageIndex { get; set; } = 1;
            public int PageSize { get; set; } = int.MaxValue;
            public string? CategoryId { get; set; }
        }

        public PhotoController(IPhotoService iPhotoService, CosXml cosClient)
        {
            _iPhotoService = iPhotoService;
            _cosClient = cosClient;
        }

        /// <summary>
        /// 获取所有照片列表
        /// </summary>
        /// <returns></returns>

        [AllowAnonymous] // 添加此特性允许匿名访问
        [HttpGet]
        public async Task<ApiResult> GetList()
        {
            var types = await _iPhotoService.QueryAsync();
            if (types.Count == 0) return ApiResultHelper.Error("没有更多图片");
            return ApiResultHelper.Success(types, true);
        }
        /// <summary>
        /// 通过分类查询图片列表
        /// </summary>
        /// <param name="categoryId">分类ID</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<ApiResult> GetPhotosByCategory(string categoryId)
        {
            if (string.IsNullOrEmpty(categoryId))
            {
                return ApiResultHelper.Error("分类ID不能为空");
            }

            try
            {
                var photos = await _iPhotoService.QueryAsync(p => p.CategoryId == categoryId);

                if (photos == null || !photos.Any())
                {
                    return ApiResultHelper.Error("该分类下没有图片");
                }

                return ApiResultHelper.Success(photos, true);
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"查询失败，服务器异常: {ex.Message}");
            }
        }
        /// <summary>
        /// 照片详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="iMapper"></param>
        /// <returns></returns>
        [AllowAnonymous] // 添加此特性允许匿名访问
        [HttpGet]
        public async Task<ApiResult> GetPhotoDetail(string id, [FromServices] IMapper iMapper)
        {
            var data = await _iPhotoService.FindAsync(id);
            if (data == null) return ApiResultHelper.Error("没有找到该图片");
            var photoDto = iMapper.Map<PhotoDTO>(data);
            return ApiResultHelper.Success(photoDto, true);
        }
        /// <summary>
        /// 照片分页查询
        /// </summary>
        /// <param name="iMapper"></param>
        /// <param name="req"></param>
        /// <returns></returns>
        [AllowAnonymous] // 添加此特性允许匿名访问
        [HttpPost]
        public async Task<ApiResult> GetPageList([FromServices] IMapper iMapper, [FromBody] PageListRequest req)
        {
            RefAsync<int> total = 0;
            Expression<Func<Photo, bool>> func = u => true;
            List<Photo> photo = null;
            if (!string.IsNullOrEmpty(req.CategoryId))
            {
                func = u => u.CategoryId.Contains(req.CategoryId);
            }
            if (req.PageIndex == 1 && req.PageSize == int.MaxValue)
            {
                var allClassification = func != null ? await _iPhotoService.QueryAsync(func) : await _iPhotoService.QueryAsync();
                total = photo.Count;
                photo = allClassification;
            }
            else
            {
                photo = await _iPhotoService.QueryAsync(func ?? (u => true), req.PageIndex, req.PageSize, total);
            }
            try
            {
                var photoDTO = iMapper.Map<List<PhotoDTO>>(photo);
                return ApiResultHelper.Success(photoDTO, total, true);
            }
            catch (Exception)
            {
                return ApiResultHelper.Error("服务器异常");
            }
        }

        /// <summary>
        /// 创建照片
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Create(CreatePhotoRequestInput req)
        {
            var uploadedPhotos = new List<Photo>();
            foreach (var item in req.Url)
            {
                if (item.Length == 0)
                {
                    return ApiResultHelper.Error("请上传图片");
                }
                Photo photo = new Photo
                {
                    Id = GuidCombGenerator.GenerateCombGuid32(),
                    Url = item,
                    CategoryId = req.CategoryId,
                    CreateAt = DateTime.Now,
                };
                bool created = await _iPhotoService.CreateAsync(photo);
                if (created)
                {
                    uploadedPhotos.Add(photo);
                }
                else
                {
                    return ApiResultHelper.Error("添加失败，服务器异常");
                }
            }
            return ApiResultHelper.Success(uploadedPhotos, true);
        }

        /// <summary>
        /// 编辑照片
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Edit(EditPhotoRequestInput req)
        {
            var photo = await _iPhotoService.FindAsync(req.Id);
            if (photo == null) return ApiResultHelper.Error("没有找到该照片");
            photo.Url = req.Url;
            photo.CategoryId = req.CategoryId;
            bool b = await _iPhotoService.EditAsync(photo);
            if (!b) return ApiResultHelper.Error("修改失败，服务器异常");
            return ApiResultHelper.Success(photo, b);
        }

        /// <summary>
        /// 删除照片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Delete(DeletePhotoRequestInput req)
        {
            bool b = await _iPhotoService.DeleteAsync(req.Id);
            if (!b) return ApiResultHelper.Error("删除失败，服务器异常");
            return ApiResultHelper.Success(null, b);
        }
    }
}
